package com.example.guava;

import com.google.common.util.concurrent.RateLimiter;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 1.RateLimiter(令牌桶算法限流器)
 */
public class RateLimitDemo {
    public static void main(String[] args) {
        // 创建一个每秒允许2个请求的限流器
        RateLimiter rateLimiter = RateLimiter.create(2);
        // 创建线程池
        ExecutorService es = Executors.newFixedThreadPool(1);
        for (int i = 0; i < 20; i++) {
            long prev = System.currentTimeMillis();
            // 限流器限流
            rateLimiter.acquire();
            // 提交任务异步执行
            es.execute(() -> {
                long cur = System.currentTimeMillis();
                // 打印任务开始执行时间
                System.out.println(cur - prev);
            });
        }
    }
}